<template>
  <div class="beautician-container">
    <div class="header">
      <h2>美容师管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增美容师
      </el-button>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable style="width: 150px" />
        </el-form-item>
        <el-form-item label="职位">
          <el-select v-model="searchForm.position" placeholder="请选择职位" clearable style="width: 150px">
            <el-option label="高级美容师" value="SENIOR" />
            <el-option label="中级美容师" value="INTERMEDIATE" />
            <el-option label="初级美容师" value="JUNIOR" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="在职" value="1" />
            <el-option label="离职" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="imageUrl" label="头像" width="80">
          <template #default="{ row }">
            <el-avatar v-if="row.imageUrl" :src="row.imageUrl" :size="50" />
            <el-avatar v-else :size="50">{{ row.name?.charAt(0) }}</el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="position" label="职位" width="120">
          <template #default="{ row }">
            {{ row.position === 'SENIOR' ? '高级美容师' : (row.position === 'INTERMEDIATE' ? '中级美容师' : '初级美容师') }}
          </template>
        </el-table-column>
        <el-table-column prop="experience" label="经验" width="80">
          <template #default="{ row }">
            {{ row.experience }}年
          </template>
        </el-table-column>
        <el-table-column prop="specialty" label="专业特长" width="200" show-overflow-tooltip />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" text @click="handleEdit(row)">编辑</el-button>
            <el-button type="warning" text @click="handleRelateProjects(row)">关联项目</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增美容师' : '编辑美容师'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入美容师姓名" />
        </el-form-item>
        
        <el-form-item label="头像" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            :action="uploadAction"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :headers="uploadHeaders"
            :on-error="handleUploadError"
            accept="image/*"
            drag
          >
            <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
            <div v-else class="el-upload__text">
              <el-icon><Plus /></el-icon>
              <div>点击或拖拽上传头像</div>
            </div>
          </el-upload>
          <el-input v-if="form.imageUrl" v-model="form.imageUrl" placeholder="图片地址" style="display: none;">
            <template #append>
              <el-button @click="form.imageUrl = ''" icon="Close" />
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="职位" prop="position">
          <el-select v-model="form.position" placeholder="请选择职位" style="width: 100%">
            <el-option label="高级美容师" value="SENIOR" />
            <el-option label="中级美容师" value="INTERMEDIATE" />
            <el-option label="初级美容师" value="JUNIOR" />
          </el-select>
        </el-form-item>

        <el-form-item label="从业经验" prop="experience">
          <el-input-number
            v-model="form.experience"
            :min="0"
            :max="50"
            placeholder="请输入从业经验年数"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="专业特长" prop="specialty">
          <el-input
            v-model="form.specialty"
            type="textarea"
            :rows="3"
            placeholder="请输入专业特长描述"
          />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :value="1">在职</el-radio>
            <el-radio :value="0">离职</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 关联项目对话框 -->
    <el-dialog
      v-model="projectDialogVisible"
      title="关联美容项目"
      width="600px"
    >
      <el-transfer
        v-model="selectedProjects"
        :data="allProjects"
        :titles="['可选项目', '已关联项目']"
        :props="{
          key: 'id',
          label: 'name'
        }"
        filterable
        filter-placeholder="请输入项目名称"
      />
      
      <template #footer>
        <el-button @click="projectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveProjectRelation" :loading="projectLoading">
          保存
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules, UploadProps } from 'element-plus'
import { Plus, Close } from '@element-plus/icons-vue'
import type { Beautician } from '@/api/beauticians'
import { getBeauticians, createBeautician, updateBeautician, deleteBeautician, getBeauticianProjects, updateBeauticianProjects } from '@/api/beauticians'
import { getProjectList } from '@/api/projects'
import type { Project } from '@/api/projects'
import { useAuthStore } from '@/stores/auth'

const authStore = useAuthStore()

const searchForm = reactive({
  name: '',
  position: '',
  status: ''
})

const tableData = ref<Beautician[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0
})

const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const submitLoading = ref(false)
const formRef = ref<FormInstance>()

// 关联项目相关
const projectDialogVisible = ref(false)
const projectLoading = ref(false)
const currentBeautician = ref<Beautician | null>(null)
const allProjects = ref<Project[]>([])
const selectedProjects = ref<number[]>([])

const form = reactive<Partial<Beautician>>({
  name: '',
  position: '',
  experience: 0,
  specialty: '',
  imageUrl: '',
  phone: '',
  email: '',
  status: 1
})

const formRules: FormRules = {
  name: [{ required: true, message: '请输入美容师姓名', trigger: 'blur' }],
  position: [{ required: true, message: '请选择职位', trigger: 'change' }],
  experience: [
    { required: true, message: '请输入从业经验', trigger: 'blur' },
    { type: 'number', min: 0, max: 50, message: '经验年数应在0-50年之间', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  status: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 上传相关
const uploadAction = '/api/salon/component/uploadImage'
const uploadHeaders = {
  Authorization: `Bearer ${authStore.token}`
}

const handleUploadSuccess: UploadProps['onSuccess'] = (response) => {
  if (response?.data) {
    form.imageUrl = response.data
    ElMessage.success('头像上传成功')
  }
}

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB！')
    return false
  }
  return true
}

const handleUploadError: UploadProps['onError'] = (error: any) => {
  let errorMessage = '头像上传失败'
  if (error.status === 413) {
    errorMessage = '文件过大，请选择小于5MB的图片'
  }
  ElMessage.error(errorMessage)
}

const loadData = async () => {
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    const { records, total } = await getBeauticians(params)
    tableData.value = records
    pagination.total = total
  } catch (error) {
    console.error('加载数据失败:', error)
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  searchForm.name = ''
  searchForm.position = ''
  searchForm.status = ''
  handleSearch()
}

const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  loadData()
}

const handleCurrentChange = (val: number) => {
  pagination.current = val
  loadData()
}

const resetForm = () => {
  Object.assign(form, {
    name: '',
    position: '',
    experience: 0,
    specialty: '',
    imageUrl: '',
    phone: '',
    email: '',
    status: 1
  })
}

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: Beautician) => {
  dialogType.value = 'edit'
  Object.assign(form, row)
  dialogVisible.value = true
}

const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        if (dialogType.value === 'add') {
          await createBeautician(form)
          ElMessage.success('添加成功')
        } else {
          await updateBeautician(form)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('提交失败:', error)
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const formatDate = (date: string) => {
  return new Date(date).toLocaleDateString('zh-CN')
}

// 关联项目相关方法
const handleRelateProjects = async (row: Beautician) => {
  currentBeautician.value = row
  projectLoading.value = true
  
  try {
    // 获取所有项目
    const projectsResponse = await getProjectList()
    allProjects.value = projectsResponse || []
    
    // 获取美容师已关联的项目
    const relatedResponse = await getBeauticianProjects(row.id)
    selectedProjects.value = relatedResponse?.map((item: any) => item.id) || []
    
    projectDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取项目数据失败')
    console.error(error)
  } finally {
    projectLoading.value = false
  }
}

const handleSaveProjectRelation = async () => {
  if (!currentBeautician.value) return
  
  projectLoading.value = true
  try {
    await updateBeauticianProjects(currentBeautician.value.id, selectedProjects.value)
    ElMessage.success('关联项目更新成功')
    projectDialogVisible.value = false
  } catch (error) {
    ElMessage.error('关联项目更新失败')
    console.error(error)
  } finally {
    projectLoading.value = false
  }
}

const handleDelete = async (row: Beautician) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除美容师 "${row.name}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteBeautician(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.beautician-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 120px;
  height: 120px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader .avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.avatar-uploader .el-upload__text {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #8c939d;
  font-size: 12px;
}

.avatar-uploader .el-icon-plus {
  font-size: 24px;
  margin-bottom: 8px;
}
</style>